package com.hethongviet.job;

import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import com.hethongviet.job.helpers.Base64;
import com.hethongviet.job.helpers.CodeResult;
import com.hethongviet.job.helpers.JSONAttributes;
import com.hethongviet.job.helpers.JSONHelper;
import com.hethongviet.job.helpers.ServiceHelper;
import com.hethongviet.job.helpers.database.CommentSQLite;
import com.hethongviet.job.helpers.database.LoginInfoSQLite;
import com.hethongviet.job.helpers.database.ProjectSQLite;
import com.hethongviet.job.helpers.database.TaskSQLite;
import com.hethongviet.job.models.Project;
import com.hethongviet.job.models.User;
import com.hethongviet.job.pages.AboutActivityLeft;
import com.hethongviet.job.pages.AboutActivityRight;
import com.hethongviet.job.pages.MainActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

public class JobTrackingActivity extends Activity
{
	private EditText _editTextUsername = null;
	private EditText _editTextPassword = null;
	private EditText _editTextActivationCode = null;
	private EditText _editTextDomain = null;

	private CheckBox _checkBoxAutoLogin = null;

	private Button _buttonLogin = null;
	private Button _buttonCancel = null;
	private Button _buttonAboutLeft = null;
	private Button _buttonAboutRight = null;

	private String _loginResultFail = null;
	private LoginInfoSQLite _loginInfoSQLite = null;
	private ProjectSQLite _projectSQLite = null;
	private TaskSQLite _taskSQLite = null;
	private CommentSQLite _commentSQLite = null;

	public JobTrackingActivity()
	{
		_loginInfoSQLite = new LoginInfoSQLite(this);
		_projectSQLite = new ProjectSQLite(this);
		_taskSQLite = new TaskSQLite(this);
		_commentSQLite = new CommentSQLite(this);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		/* Full screen */
		AppMain.prepareWindow(this);

		/* First database, that will create all table */
		if (Config.USE_DATABASE)
			_loginInfoSQLite = new LoginInfoSQLite(this);

		setContentView(R.layout.main);

		_buttonLogin = (Button) findViewById(R.id.buttonLogin);
		_buttonCancel = (Button) findViewById(R.id.buttonCancel);
		_editTextActivationCode = (EditText) findViewById(R.id.editTextAcitvationCode);
		_editTextPassword = (EditText) findViewById(R.id.editTextPassword);
		_editTextUsername = (EditText) findViewById(R.id.editTextUsername);
		_editTextDomain = (EditText) findViewById(R.id.editTextDomain);

		_checkBoxAutoLogin = (CheckBox) findViewById(R.id.checkboxAutoLogin);

		_buttonAboutLeft = (Button) findViewById(R.id.buttonAboutLeft);
		_buttonAboutRight = (Button) findViewById(R.id.buttonAboutRight);
		_buttonAboutLeft.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				Intent intent = new Intent(JobTrackingActivity.this,
						AboutActivityLeft.class);
				startActivity(intent);
			}
		});
		_buttonAboutRight.setOnClickListener(new OnClickListener()
		{

			public void onClick(View arg0)
			{
				Intent intent = new Intent(JobTrackingActivity.this,
						AboutActivityRight.class);
				startActivity(intent);
			}
		});

		/* Load data if last remembering */
		if (Config.USE_DATABASE)
		{
			AppMain._user = _loginInfoSQLite.getUser();
		}

		AppMain.debug("start up -  get info");
		if (AppMain._user != null && AppMain._user.isAutoLogin())
		{
			AppMain.debug("start up -  login remember");
			_editTextActivationCode.setText(AppMain._user.getActivationCode());
			_editTextPassword.setText(AppMain._user.getPassword());
			_editTextUsername.setText(AppMain._user.getUsername());
			_checkBoxAutoLogin.setChecked(AppMain._user.isAutoLogin());
			_editTextDomain.setText(AppMain._user.getDomain());

			if (!AppMain._justLogined)
			{
				login();
			}
		}
		else
		{
			AppMain.debug("start up -  login remember none");
			AppMain._user = new User();
		}

		/* Remember data */
		_checkBoxAutoLogin.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked)
			{
				updateLogin();
			}
		});

		if (Config.IS_DEBUG)
		{
			_editTextActivationCode.setText("7ITTWBNR");
			_editTextPassword.setText("123456789");
			_editTextUsername.setText("dinhngoctan.cntt@gmail.com");
			_editTextDomain.setText("vsys");
		}

		if (Config.IS_DEBUG_DOMAIN)
		{
			_editTextActivationCode.setText("Z5NU6BEW");
			_editTextPassword.setText("123456");
			_editTextUsername.setText("lehaiyen1982@gmail.com");
			_editTextDomain.setText("linhan");
		}

		_buttonCancel.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				/* Reset all fields */
				_editTextActivationCode.setText("");
				_editTextPassword.setText("");
				_editTextUsername.setText("");
				_editTextDomain.setText("");
				_checkBoxAutoLogin.setChecked(false);
				updateLogin();
			}
		});

		_buttonLogin.setOnClickListener(new OnClickListener()
		{
			public void onClick(View arg0)
			{
				String username = _editTextUsername.getText().toString();
				if (username == null || username.equalsIgnoreCase(""))
				{
					AppMain.showAlert(JobTrackingActivity.this,
							getString(R.string.textErrorEmptyInput) + " "
									+ getString(R.string.textUsername), false);
					return;
				}

				String password = _editTextPassword.getText().toString();
				if (password == null || password.equalsIgnoreCase(""))
				{
					AppMain.showAlert(JobTrackingActivity.this,
							getString(R.string.textErrorEmptyInput) + " "
									+ getString(R.string.textPassword), false);
					return;
				}

				String activationCode = _editTextActivationCode.getText().toString();
				if (activationCode == null
						|| activationCode.equalsIgnoreCase(""))
				{
					AppMain.showAlert(JobTrackingActivity.this,
							getString(R.string.textErrorEmptyInput) + " "
									+ getString(R.string.textAcitvationCode),
							false);
					return;
				}

				if (activationCode.length() != AppMain.ACTIVATION_CODE_CHAR_LENGTH)
				{
					AppMain.showAlert(JobTrackingActivity.this,
							R.string.textErrorMessageWrongActivationCodeLength,
							false);
					return;
				}

				updateLogin();
				login();

			}
		});
	}

	private void updateLogin()
	{
		updateUserInfo();

		if (Config.USE_DATABASE)
		{
			User user = _loginInfoSQLite.getUser();

			_loginInfoSQLite.insertOneUser(AppMain._user);

			if (user == null
					|| !user.getDomain().equalsIgnoreCase(
							AppMain._user.getDomain()))
			{
				/* Delete all data */
				_projectSQLite = new ProjectSQLite(
							JobTrackingActivity.this);
				
				_projectSQLite.deleteAll();

				_taskSQLite = new TaskSQLite(JobTrackingActivity.this);
				_taskSQLite.deleteAll();

				_commentSQLite = new CommentSQLite(
						JobTrackingActivity.this);

				_commentSQLite.deleteAll();

				AppMain._listProjects.clear();
				AppMain._listProjectsShow.clear();
				AppMain._listTasksAll.clear();
				AppMain._listTasksShow.clear();
				AppMain._listComments.clear();
			}
		}
	}

	private void login()
	{
		AppMain._isSMSEnable = false;
		if (!Config.IS_NETWORKING_ENABLE)
		{
			AppMain._codeResultService = doLogin(
					_editTextUsername.getText().toString(),
					_editTextPassword.getText().toString(),
					_editTextActivationCode.getText().toString());
			AppMain.hideProgressDialog();
			return;
		}
		showProgressBar();

		new Thread(new Runnable()
		{
			public void run()
			{
				try
				{
					Thread.sleep(1000);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}

				if (AppMain.isNetworkAvailable(JobTrackingActivity.this))
				{
					AppMain.debug("Network available!!");

					AppMain._codeResultService = doLogin(
							_editTextUsername.getText().toString(),
							_editTextPassword.getText().toString(),
							_editTextActivationCode.getText().toString());
				}
				else
				/* Offline */
				{
					AppMain.debug("Network not available!!");
					if (/* Check the database if exist */
					AppMain.isDatabaseExist(JobTrackingActivity.this)
							&&
							/* Check the table Project if exist */
							_projectSQLite.isTableExist()
							&&
							/* Check the table Task if exist */
							_taskSQLite.isTableExist())
					{
						AppMain.debug("Database available!!");
						/* Check the SIM */
						if (AppMain.isSIMExist(JobTrackingActivity.this))
						{
							AppMain.debug("SIM available!!");
							AppMain._codeResultService = CodeResult.SUCCESS_DETECT_SIM;
						}
						else
						{
							AppMain.debug("SIM not available!!");
							AppMain._codeResultService = CodeResult.FAIL_DETECT_SIM;
						}
					}
					else
					{
						AppMain.debug("Network not available and in the first time use this software");
						AppMain._codeResultService = CodeResult.DB_NOT_EXIST;
					}
				}
				AppMain.hideProgressDialog();
			}
		}).start();
	}

	private void updateUserInfo()
	{
		AppMain._user.setActivationCode(_editTextActivationCode.getText().toString());
		AppMain._user.setPassword(_editTextPassword.getText().toString());
		AppMain._user.setUsername(_editTextUsername.getText().toString());
		AppMain._user.setAutoLogin(_checkBoxAutoLogin.isChecked());
		AppMain._user.setDomain(_editTextDomain.getText().toString());
	}

	private void gotoPageMain()
	{
		AppMain._justLogined = true;
		Intent intent = new Intent(JobTrackingActivity.this, MainActivity.class);
		startActivity(intent);
	}

	private void doLoginOffline(String username, String password,
			String activationCode)
	{
		AppMain.debug("Login offline.............");


		ProjectSQLite projectSQLite = new ProjectSQLite(
					JobTrackingActivity.this);
		AppMain._listProjects = projectSQLite.getAll();

		AppMain._listTasksAll = _taskSQLite.getAll();

		AppMain.debug(" number of projects:" + AppMain._listProjects.size());
		AppMain.debug(" number of tasks:" + AppMain._listTasksAll.size());
		if (AppMain._listProjects.size() != 0)
		{
			AppMain._listProjectsShow = new Vector<Project>();
			for (Project project : AppMain._listProjects)
			{
				AppMain._listProjectsShow.add(project);
			}
		}
		gotoPageMain();
	}

	private CodeResult doLogin(String username, String password,
			String activationCode)
	{
		CodeResult codeResult = CodeResult.NONE;

		String resultString = null;
		if (Config.IS_NETWORKING_ENABLE)
		{
			String appName = getString(R.string.textAppNameComon)
					+ (Config.VERSION_STANDARD ? "_standard" : "_pro");
			resultString = ServiceHelper.doLogin(username, password,
					activationCode, appName);
		}
		else
			resultString = "{\"FK_UserID\":\"d709460b-0f94-4e6b-aca7-4ceb7f2dc712\",\"UserName\":\"dinhngoctan.cntt@gmail.com\",\"PasswordLogin\":\"wI6wL7kuliDrQ+19K7FqmMdHqex522o+MFENwglKDUA=\",\"FK_MemberID\":\"53ec32b9-57e8-4306-a418-d87a44e7c0fc\",\"IsManagerJob\":\"False\",\"CompanyName\":\"VSYS JOIN STOCK COMPANY\"}&";

		/* Return the error code 0, 1, 2, 3 */
		if (resultString == null)
		{
			AppMain.debug("Error: string from login null");
			codeResult = CodeResult.ERROR_NETWORK;
		}
		else if (resultString.length() < 3)
		{
			int error = -1;
			try
			{
				error = Integer.parseInt(resultString);
			} catch (NumberFormatException numberFormatException)
			{
				numberFormatException.printStackTrace();
			}
			String errorString = null;
			switch (error)
			{
				case AppMain.ERROR_CODE_ACTIVATION_CODE_OUT_OF_DATE:
					errorString = getString(R.string.textErrorMessageActivationCodeOutOfDate);
					break;
				case AppMain.ERROR_CODE_ACTIVATION_CODE_USED_BY_OTHER:
					errorString = getString(R.string.textErrorMessageAcivationCodeUsedByOther);
					break;
				case AppMain.ERROR_CODE_WRONG_ACTIVATION_CODE:
					errorString = getString(R.string.textErrorMessageWrongActivationCode);
					break;
				case AppMain.ERROR_CODE_WRONG_USERNAME_OR_PASSWORD:
					errorString = getString(R.string.textErrorMessageWrongUsernameOrPassword);
					break;
				default:
					errorString = getString(R.string.textErrorNetwork);
					// errorString = resultString;
					break;
			}
			AppMain.debug("Error: fail authority!");
			_loginResultFail = errorString;
			codeResult = CodeResult.FAIL_LOGIN;
		}
		else
		{
			/* Return JSON : Successful */
			AppMain._user.setUsername(username);
			AppMain._user.setPassword(password);
			AppMain._user.setActivationCode(activationCode);
			AppMain._user.setAutoLogin(_checkBoxAutoLogin.isChecked());
			AppMain._user.setDomain(_editTextDomain.getText().toString());
			codeResult = CodeResult.SUCCESS_LOGIN;
			/* Remove char & */
			resultString = resultString.substring(0, resultString.length() - 1);
			JSONObject jsonObject = null;
			try
			{
				jsonObject = new JSONObject(resultString);
			} catch (JSONException e)
			{
				e.printStackTrace();
				AppMain.debug("Error: string from login wrong format 2");
				codeResult = CodeResult.ERROR_NETWORK;
			}

			if (codeResult == CodeResult.SUCCESS_LOGIN)
			{
				if (jsonObject != null)
				{
					AppMain._user.setId(JSONHelper.getString(jsonObject,
							JSONAttributes.USER_ID));
					AppMain._user.setMemberId(JSONHelper.getString(jsonObject,
							JSONAttributes.USER_MEMBER_ID));
					AppMain._user.setManagerJobs(Boolean.parseBoolean(JSONHelper.getString(
							jsonObject, JSONAttributes.USER_IS_MANAGER_JOB)));
					AppMain._user.setCompanyName(JSONHelper.getString(
							jsonObject, JSONAttributes.USER_COMPANY_NAME));

					AppMain._user.setMemberName(JSONHelper.getString(
							jsonObject, JSONAttributes.USER_MEMBER_NAME));
					AppMain._user.setMemberCode(JSONHelper.getString(
							jsonObject, JSONAttributes.USER_MEMBER_CODE));

					String imageBase64 = JSONHelper.getString(jsonObject,
							JSONAttributes.USER_IMAGE);
					try
					{
						byte[] decodedString = Base64.decode(imageBase64,
								Base64.DEFAULT);
						Bitmap decodeBitmap = BitmapFactory.decodeByteArray(
								decodedString, 0, decodedString.length);

						AppMain._user.setImageBitmap(decodeBitmap);
					} catch (IllegalArgumentException e)
					{
						e.printStackTrace();
					}
				}

				/* Get data */
				if (Config.IS_LOGIN_UPDATE || !Config.USE_DATABASE)
				{
					if (AppMain.doGetProjects(this, username) == CodeResult.SUCCESS_GET_PROJECTS
							&& AppMain.doGetTasksAll(this) == CodeResult.SUCCESS_GET_TASKS)
					{
						/* Go to the main page */
						gotoPageMain();
					}
					else
					{
						codeResult = CodeResult.ERROR_NETWORK;
						AppMain.hideProgressDialog();
					}
				}
				else
				{

					AppMain._listProjects = _projectSQLite.getAll();
					AppMain._listTasksAll = _taskSQLite.getAll();

					AppMain.debug(" number of projects:"
							+ AppMain._listProjects.size());
					AppMain.debug(" number of tasks:"
							+ AppMain._listTasksAll.size());

					if (AppMain._listProjects.size() == 0
							|| AppMain._listTasksAll.size() == 0)
					{
						if (AppMain._listProjects.size() == 0)
							AppMain._codeResultService = AppMain.doGetProjects(
									this, username);

						if (AppMain._listTasksAll.size() == 0)
							AppMain._codeResultService = AppMain.doGetTasksAll(JobTrackingActivity.this);

						if (AppMain._codeResultService == CodeResult.SUCCESS_GET_TASKS
								|| AppMain._codeResultService == CodeResult.SUCCESS_GET_PROJECTS)
						{
							gotoPageMain();
						}
					}
					else
					{
						AppMain._listProjectsShow = new Vector<Project>();
						for (Project project : AppMain._listProjects)
						{
							AppMain._listProjectsShow.add(project);
						}
						gotoPageMain();
					}
				}
			}
		}
		return codeResult;
	}

	@Override
	protected void onPause()
	{
		AppMain.hideProgressDialog();
		AppMain._codeResultService = CodeResult.NONE;
		AppMain._isDoneLoading = false;
		enableAllClick(true);
		super.onPause();
	}

	@Override
	public void onBackPressed()
	{
		updateLogin();
		AppMain._justLogined = false;

		AppMain.hideProgressDialog();
		AppMain._isDoneLoading = false;

		super.onBackPressed();
	}

	@Override
	protected void onDestroy()
	{
		AppMain.debug("Destroy app!!!!!!!!!!!!!!!!");
		super.onDestroy();
		System.exit(0);
	}

	private void showProgressBar()
	{
		AppMain.showProgress(this);
		enableAllClick(false);
	}

	private void enableAllClick(boolean enable)
	{
		_buttonCancel.setClickable(enable);
		_buttonLogin.setClickable(enable);
		_buttonAboutLeft.setClickable(enable);
		_buttonAboutRight.setClickable(enable);
		_checkBoxAutoLogin.setClickable(enable);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus)
	{
		if (AppMain._isDoneLoading)
		{
			switch (AppMain._codeResultService)
			{
				case ERROR_NETWORK:
					AppMain.showAlert(this, R.string.textErrorNetwork, false);
					break;
				case FAIL_LOGIN:
					if (_loginResultFail != null)
					{
						AppMain.showAlert(this, _loginResultFail, false);
						_loginResultFail = null;
					}
					break;
				case FAIL_DETECT_SIM:
					AppMain.showAlert(this, R.string.textMessageInsertSMS,
							false);
					break;
				case SUCCESS_DETECT_SIM:
					OnClickListener onClickListenerYES = new OnClickListener()
					{
						public void onClick(View v)
						{
							AppMain._isSMSEnable = true;
							AppMain.debug("Login offline!!");
							/* Log in from database */

							doLoginOffline(
									_editTextUsername.getText().toString(),
									_editTextPassword.getText().toString(),
									_editTextActivationCode.getText().toString());
						}
					};

					AppMain.showAlert(this, R.string.textMessageSMSEnable,
							false, onClickListenerYES);

					break;
				case DB_NOT_EXIST:
					AppMain.showAlert(this,
							R.string.textMessageNetworkNotAvailable, false);
					break;

				default:
					break;
			}
			AppMain.debug("window changed!!!");
			AppMain._codeResultService = CodeResult.NONE;
			AppMain._isDoneLoading = false;
			enableAllClick(true);
		}
		super.onWindowFocusChanged(hasFocus);
	}
}
